import React, { forwardRef, useImperativeHandle, useState } from "react";
import { Tree, Tabs, Button, DatePicker, Dropdown, Input, Tooltip, Empty, Form } from 'antd';
import {
    DownOutlined,
    FrownFilled,
    SendOutlined,
    UndoOutlined,
    RedoOutlined,
    CheckOutlined,
    RightOutlined,
    ReadOutlined,
    DeleteOutlined,
    PlusCircleOutlined,
    EditOutlined,
    CopyOutlined,
    TagOutlined,
    ExclamationCircleOutlined,
} from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
import { TopicTemplateType, TopicType } from "../../../utils/types";
import type { RadioChangeEvent, MenuProps } from 'antd';
import { addTopicIdForTopicList, addTreePropertyForList, commonErrorMsg, formatTime, generateTreeData, getUuid, toastShort } from "../../../utils";
import systemApi from "../../../api/system";

interface Props {
    jumpToDetails?: Function
    topicTemplate?: TopicTemplateType,
    openEditModal?: Function
    onFinish?: Function
    modal?: any
};

const TopicTemplateCard = (props: Props, ref: any) => {
    useImperativeHandle(ref, () => ({
        // openModal: openModal
    }));

    const {
        topicTemplate,
        jumpToDetails,
        openEditModal,
        onFinish,
        modal
    } = props;

    const [dropDownOpend, setDropDownOpend] = useState(false);
    const [copyLoading, setCopyLoading] = useState(false);
    const [deleteLoading, setDeleteLoading] = useState(false);

    const getTopicTemplateTreeData = () => {
        const treeData = generateTreeData(addTreePropertyForList(topicTemplate.topicList));
        return treeData;
    }

    const onMenuClick: MenuProps['onClick'] = (e) => {
        console.log('click', e);
    };

    const handleJumpToDetails = () => {
        jumpToDetails && jumpToDetails(topicTemplate);
    };

    const handleOpenEditModal = () => {
        openEditModal && openEditModal(topicTemplate);
        setDropDownOpend(false)
    }

    const handleCreateCopy = () => {
        setCopyLoading(true);
        let params: TopicTemplateType = {
            name: `${topicTemplate.name}(副本)`,
            sortNumber: getUuid(8),
            sort: '1',
            topicList: addTopicIdForTopicList(topicTemplate.topicList),
            remark: topicTemplate.remark
        }
        systemApi.addTopicTemplate(params)
            .then(res => {
                setCopyLoading(false);
                setDropDownOpend(false)
                onFinish && onFinish();
            })
            .catch(err => {
                setCopyLoading(false);
                toastShort('error', commonErrorMsg)
            })
    };

    const handleDelete = () => {
        modal.confirm({
            title: '温馨提示',
            icon: <ExclamationCircleOutlined />,
            content: '确认删除此大纲模版？此操作不可撤销',
            okText: '确认',
            cancelText: '取消',
            centered: true,
            onOk: comfirmToDeleteTopicTemplate,
            okButtonProps: { loading: deleteLoading }
        });
    }

    const comfirmToDeleteTopicTemplate = () => {
        setDeleteLoading(true);
        let params = {
            ids: [topicTemplate.id]
        }
        systemApi.deleteTopicTemplate(params)
            .then(res => {
                setDeleteLoading(false);
                setDropDownOpend(false)
                onFinish && onFinish();
            })
            .catch(err => {
                setDeleteLoading(false);
                toastShort('error', commonErrorMsg)
            })
    }

    const dropdownRender = (e) => {
        // console.log("dropdownRender---->", e)
        return (
            <div className="flex-col dropdown-button-group">
                <Tooltip
                    placement={'right'}
                    title={'在当前的模版基础上复制一个新的大纲模版，以便快速生成不同的模版。'}
                >
                    <Button
                        type={'text'}
                        icon={<CopyOutlined />}
                        onClick={handleCreateCopy}
                        loading={copyLoading}
                    >
                        创建副本
                    </Button>
                </Tooltip>
                <div className="custom-border" style={{ width: 72 }}></div>
                <Button
                    type={'text'}
                    icon={<EditOutlined />}
                    onClick={handleOpenEditModal}
                >
                    基本信息
                </Button>
                <div className="custom-border" style={{ width: 72 }}></div>
                <Button
                    type={'text'}
                    icon={<DeleteOutlined />}
                    loading={deleteLoading}
                    onClick={comfirmToDeleteTopicTemplate}
                    danger
                >
                    删除模版
                </Button>
            </div>
        )
    }

    const adaptNodeIcon = (node: TopicType) => {
        let nodeIcon = <i className='iconfont-1 ghzs-gray-shebei' />;
        switch (node.topicType) {
            case 'device':
                switch (node.deviceType) {
                    case 'S':
                        nodeIcon = <i className='iconfont-1 ghzs-gray-shebei' />
                        break;
                    case 'X':
                        nodeIcon = <i className='iconfont-1 ghzs-gray-sheshi' />
                        break;
                }
                break;
            case 'text':
                nodeIcon = <i className='iconfont-1 ghzs-gray-wenben' />
                break;
            default:
                break;
        }
        return nodeIcon;
    }

    const topicNodeRender = (nodeData: TopicType) => {
        // console.log("nodeData---->", nodeData)
        return (
            <div
                className='custom-tree-node'
            >
                <div className='flex-row topic-tree-node'>
                    <div className='topic-tree-node-icon'>
                        {adaptNodeIcon(nodeData)}
                    </div>
                    <p className='single-line-text' style={{ width: 420 }}>{nodeData.title}</p>
                </div>
            </div>
        );
    };

    const onOpenChange = (value: boolean) => {
        setDropDownOpend(value)
    };

    return (
        <div
            className={'flex-col topic-template-card'}
        >
            <div className='flex-col topic-template-card-cover'>
                {
                    topicTemplate.topicList && topicTemplate.topicList.length ?
                        <Tree
                            showLine
                            switcherIcon={<DownOutlined />}
                            treeData={getTopicTemplateTreeData()}
                            className={'small-tree'}
                            //@ts-ignore
                            titleRender={topicNodeRender}
                            defaultExpandAll
                            blockNode
                        />
                        :
                        <div className="card-empty-container">
                            <Empty
                                image={Empty.PRESENTED_IMAGE_SIMPLE}
                                description={"暂无大纲配置"}
                            />
                        </div>
                }
            </div>
            <div className='flex-col topic-template-card-footer'>
                <p className='topic-template-card-name single-line-text'>
                    {/* <TagsOutlined style={{ marginRight: 5, color: '#0f6432' }} /> */}
                    {topicTemplate.name}
                </p>
                {/* <p className='topic-template-card-desc'><span style={{ fontSize: 14 }}>{formatTime(topicTemplate.createDate)}创建</span></p> */}
                {/* <p className='topic-template-card-desc'>更新日期：<span style={{ fontSize: 14 }}>{formatTime(topicTemplate.updateDate)}</span></p> */}
                <p className='topic-template-card-desc'>{formatTime(topicTemplate.updateDate)}</p>
                <div className='flex-row topic-template-card-footer-bottom'>
                    <Dropdown.Button
                        menu={{ items: [], onClick: onMenuClick }}
                        style={{ width: 149 }}
                        onClick={handleJumpToDetails}
                        open={dropDownOpend}
                        trigger={['click']}
                        dropdownRender={dropdownRender}
                        onOpenChange={onOpenChange}
                    >
                        配置大纲模版
                    </Dropdown.Button>
                </div>
            </div>
        </div>
    )
}

export default forwardRef(TopicTemplateCard);